import resso from 'resso'
import store from 'react-native-simple-store';
import _ from 'lodash'

const AppStore = resso({
    bluetoothEnable:false,
    scanning:false,
    deviceList:[],
    msgList:[],
    currentDevice:null,
    battery:null,
    pressure:0,
    location:null,
    debugMode:false
})


export function useAppStore(){

    function updateAppState(obj){
        console.log('updateAppState:',obj);
        Object.keys(obj).forEach(key=>{
            // console.log(key);
            AppStore[key] = obj[key]
        })

    }

    const deleteDevice = (item,cb)=>{
        let newList = AppStore.deviceList.filter(it=>{
            return it.id !== item.id
        })
        AppStore.deviceList = newList

        const storeKey = `device_${item.id}`
        store.delete(storeKey).then(values=>{
            cb()
        }).catch(error=>{

        })
    }

    const addDevice = (item )=>{
        //先查重
        const findIndex = AppStore.deviceList.findIndex(it=>{
            return it.id == item.id
        })
        let newList = _.clone(AppStore.deviceList)
        if(findIndex>-1){
            //修改设备
            newList.splice(findIndex,1,item)
        }else{
            //添加设备
            newList.unshift(item)
        }
        // console.log('addDEVICE:',item);
        AppStore.deviceList = newList
        store.save('deviceList',newList)
    }

    const addMessage = (msg)=>{
        let newList = _.clone(AppStore.msgList)
        newList.unshift(msg)
        // console.log('new msgList:',newList);
        AppStore.msgList = newList
        let key = AppStore.currentDevice.id + '_message'
        store.save(key,newList)
    }

    const deleteMessage = (index,cb)=>{
        let newList = _.clone(AppStore.msgList)
        newList.splice(index,1)
        console.log('delete msg:',newList);
        AppStore.msgList = newList
        let storeKey = AppStore.currentDevice.id + '_message'
        store.save(storeKey,newList).then(values=>{
            cb()
        }).catch(error=>{

        })
    }

    return {appState:AppStore,updateAppState,deleteDevice,addDevice,addMessage,deleteMessage}
}



export default AppStore
